<template>
  <div>
    <input v-model="city" placeholder="请输入城市名称" @input="debounceInput" />
    <button @click="getWeather">查询</button>
    
    <div class="loading" v-if="loading">加载中...</div>
    
    <div v-if="weatherData">
      <div class="weather-info">
        <p>城市：{{weatherData.location.name}}</p>
        <p>温度：{{weatherData.now.temp}}°C</p>
        <p>天气状况：{{weatherData.now.text}}</p>
        <p>空气质量：{{weatherData.now.air_quality.city.quality}}</p>
      </div>
    </div>
    
    <div v-if="errorMessage" class="error">
      {{ errorMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, debounce } from 'vue';
import axios from 'axios';

const city = ref('');
const weatherData = ref(null);
const loading = ref(false);
const errorMessage = ref('');

const getWeather = async () => {
  loading.value = true;
  errorMessage.value = '';
  
  try {
    const response = await axios.get('https://api.seniverse.com/v3/weather/now.json', {
      params: {
        key: 'YOUR_API_KEY',
        location: city.value,
        language: 'zh-Hans',
        unit: 'c'
      }
    });
    
    if (response.data && response.data.results.length > 0) {
      weatherData.value = response.data.results[0];
    } else {
      throw new Error('无效的API响应数据');
    }
  } catch (error) {
    console.error('天气查询失败：', error);
    errorMessage.value = '无法获取天气数据，请检查城市名称或稍后再试';
  } finally {
    loading.value = false;
  }
};

// 添加防抖处理
const debounceInput = debounce(() => {
  if (city.value.trim() !== '') {
    getWeather();
  }
}, 500);
</script>

<style scoped>
#app {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

input {
  width: calc(100% - 80px);
  padding: 8px;
  margin-bottom: 10px;
}

button {
  width: 80px;
  padding: 8px;
  background-color: #2c3e50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #3498db;
}

.weather-info {
  margin-top: 20px;
  border-top: 2px solid #3498db;
  padding-top: 10px;
}
</style>